package kit4j.topnote;

import java.awt.Container;
import java.awt.Insets;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

import kit4j.view.cs.exception.ListNoSelectionException;
import kit4j.view.cs.swing.dialog.JFontChooser;

public class TopNote {

	private JFrame mainFrame = null;
	private Container contentPane = null;
	private JScrollPane scrollPane = null;
	private JTextArea textArea = null;
	private JFontChooser fontChooser = null;

	public TopNote(String title) {
		initMainFrame(title);
		initComponent();
		initInteraction();
	}

	private void initMainFrame(String title) {
		mainFrame = new JFrame(title);
		mainFrame.setSize(400, 500);
		mainFrame.setLocationRelativeTo(null);
	}

	private void initComponent() {
		contentPane = mainFrame.getContentPane();
		textArea = new JTextArea();
		textArea.setMargin(new Insets(3, 4, 3, 3));
		textArea.setTabSize(4);
		scrollPane = new JScrollPane(textArea);
		contentPane.add(scrollPane);
		fontChooser = new JFontChooser(mainFrame, "设置字体");
	}

	private void initInteraction() {
		mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		textArea.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent evt) {
				if (evt.isControlDown() && KeyEvent.VK_ENTER == evt.getKeyCode()) {
					mainFrame.setAlwaysOnTop(!mainFrame.isAlwaysOnTop());
				} else if (evt.isControlDown() && KeyEvent.VK_L == evt.getKeyCode()) {
					textArea.setLineWrap(!textArea.getLineWrap());
				}
			}
		});

		textArea.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent evt) {
				if (evt.isShiftDown() && KeyEvent.VK_ENTER == evt.getKeyCode()) {
					fontChooser.setSelectedFont(textArea.getFont());
					if (fontChooser.showChooseDialog() == JOptionPane.OK_OPTION) {
						try {
							textArea.setFont(fontChooser.getSelectedFont());
						} catch (ListNoSelectionException e) {
						}
					}
				}
			}
		});
	}

	public void show() {
		mainFrame.setAlwaysOnTop(true);
		mainFrame.setVisible(true);
	}

	public JFrame getMainFrame() {
		return mainFrame;
	}

	public void setMainFrame(JFrame mainFrame) {
		this.mainFrame = mainFrame;
	}

	public Container getContentPane() {
		return contentPane;
	}

	public void setContentPane(Container contentPane) {
		this.contentPane = contentPane;
	}

	public JTextArea getTextArea() {
		return textArea;
	}

	public void setTextArea(JTextArea textArea) {
		this.textArea = textArea;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				new TopNote("TopNote").show();
			}
		});
	}

}
